<template>
<div>
<div class="comment boxshw">
	<h3>评论列表</h3>
  <a-comment class="comment-main"> 
		<img class="header" style="opacity:0.8" slot="avatar" src="@/assets/header.jpg"/>
    <span class="name" slot="author">Doer1001</span>
		<span class="time en" slot="datetime">{{new Date().getTime() | setTimeFormat}}</span>    
    <div slot="content">大家好，欢迎留言，第一时间回复</div>
    <span class="replay" slot="actions" @click="goToScrollComment(true)">回复</span>
  </a-comment>
	
  <a-comment class="comment-main" v-for="item in commentList" :key="item.id">
		<a-avatar class="header"  slot="avatar">{{item.userToReply[0] | setHeaderText}}</a-avatar>
    <span class="name" slot="author">{{item.userToReply[0]}}</span>
		<span class="time en" slot="datetime">{{item.created | setTimeFormat}}</span>    
    <div slot="content">{{item.comment}}</div>
		<span class="replay" slot="actions" @click="goToReply(item,item.id)" >回复</span>
			<a-comment class="comment-main" v-for="itemSub in item.children" :key="itemSub.id"> 
				<img class="header" v-if="itemSub.userId == '100001'" style="opacity:0.8" slot="avatar" src="@/assets/header.jpg"/>
        <a-avatar v-else class="header"  slot="avatar" >{{itemSub.userToReply[0] | setHeaderText}}</a-avatar>
				
        <span class="name en" slot="author">{{itemSub.userToReply[0]}}@{{itemSub.userToReply[1]}}</span>
				<span class="time en" slot="datetime">{{itemSub.created | setTimeFormat}}</span>    
				<div slot="content">{{itemSub.comment}}</div>
				<span class="replay" slot="actions" @click="goToReply(itemSub,item.id)">回复</span>	
			</a-comment>
  </a-comment>
</div>
<div class="comment boxshw" id="commentContent"  name="commentContent">
	<h3 style="border:0; margin-bottom:0;">发表评论</h3>
	<div class="comment-content" slot="content">	
		<a-form :form="form" :wrapper-col="{ span: 24 }" layout="inline">
		<a-form-item class="comment-textbox">
			<a-textarea autocomplete="off"  v-decorator="comment" class="comment-textarea" :maxLength="200" :placeholder="placeholder"></a-textarea>
		</a-form-item>
		<div class="comment-btns">
			<template v-if="!isLogin">
				<a-form-item>
					<a-input autocomplete="off" :maxLength="15" v-decorator="username" placeholder="请输入用户名" class = "comment-input">
						<a-icon slot="prefix" type="user" style="color:rgba(0,0,0,.25)" />
					</a-input>
				</a-form-item>
				<a-form-item>
					<a-input-password autocomplete="off" :maxLength="15"  v-decorator="password" placeholder="请输入密码" class = "comment-input">
						<a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
					</a-input-password>
				</a-form-item>
			</template>
			<a-form-item>						
				<a-button class="comment-btn"  @click="handleSubmit" :loading="btnLoading" icon="form" type="primary">提交</a-button>
			</a-form-item>
		</div>
		</a-form>
	</div>
	<div class="comment-tips">
		备注：<br/>
		1.首次评论密码自定义设置，下次可用首次登录的账号和密码评论！<br/>
		2.只允许评论与开发知识相关的内容，通过审核后回复并显示！
	</div>	
</div>
</div>
</template>
<script>
import api from "@/global/api";
export default {
  data() {
    return {
			btnLoading:false,
			loginVisible:true,
			placeholder:'请输入评论内容，不能超过200字',
			form: this.$form.createForm(this, { name: 'login' }),
			username:['username',{
				rules: [
					{ required: true,  message: '用户名不能为空！'},
				  { min:3, message: '用户名至少3位!'},	
				  { pattern: /^[A-Za-z\d]+$/, message: '用户名只能包含字母和数字!'},				
			  ],
			  validateTrigger:'onBlur'
			}],
			password:['password', {rules: [
					{ required: true, message: '密码不能为空！'},
					{ min:3, message: '密码至少3位!'},	
					{ pattern: /^[A-Za-z\d_]+$/, message: '密码只能包含字母数字和下划线!'},			
				],
				validateTrigger:'onBlur'
			}],
			comment:['comment', { rules: [
					{ required: true, message: '评论内容不能为空！'},
					{ min:5, message: '评论至少5个字符!'},
				],
				validateTrigger:'onBlur'
			}],
			isLogin : false,
			commentList:[]
    }
  },
  created() {
		this.isLogin = this.$store.state.token ? true : false;
		this.contentId = this.$route.params.id;
		this.parentId = '';
		this.getComment();
  },	
  methods: {
		handleSubmit(e){
			e.preventDefault();
			this.form.validateFields( async (err, values) => {
				if(!err){
					this.btnLoading = true;
					if(!this.isLogin){
						let _param = {username:values.username,password:values.password};
						let _user = await this.$axios.post(api.addUser,_param,{progress: false});
						if(_user.code == '20000'){
							this.$cookies.set('token',_user.token)
							this.$store.commit('setToken', _user.token);
							this.addComment(values);
						}else{
							this.btnLoading = false;
							this.$message.warning(_user.msg);
						}
					}else{
						this.addComment(values);	
					}
				}	
			})
		},
		async addComment(values){
			let _paramComment = {
				contentId:this.contentId,
				comment:values.comment,
				toReply:this.toReply ? this.toReply : '',
				parentId:this.parentId ? this.parentId : 0
			}
			let addComment = await this.$axios.post(api.addComment,_paramComment,{progress: false});
			if(addComment.code == '20000'){
				setTimeout(()=>{
					this.isLogin = true;
					this.btnLoading = false;
					this.form.resetFields();
					this.getComment();
					this.$message.success('评论成功，请等待管理员审核！');						
				},500)
			}else{
				this.isLogin = true;
				this.btnLoading = false;
				this.$message.warning('评论失败，请重编辑内容！');
			}
		},
		async getComment(){
			let res = await this.$axios.get(api.getComment,{params:{id:this.contentId,page:1,pageSize:15}});
			this.commentList = res.data;
		},
		goToScrollComment(type){
			if(type){
				this.parentId = 0;
				this.placeholder = '请输入评论内容，不能超过200字';
				this.form.resetFields();	
			}
			this.$el.querySelector('#commentContent').scrollIntoView({behavior:'smooth', block:'nearest'});				
		},
		goToReply(item,_parentId){
			this.goToScrollComment(false);
			this.parentId = _parentId;
			this.toReply = item.userToReply[0];
			this.placeholder = '@'+item.userToReply[0]+':'+item.comment;
		}
	},
	filters: {
		setResUrl(val){
			return api.host+val;	
		},
		setHeaderText(val){
			var str = val.substring(0,1);
			return str;
		},
		setTimeFormat(val){
			var paddingStr = function (_str) {
				return _str.length == 1 ? "0" + _str : _str
			}
			var _curDate = new Date(val);	
			var _YY = _curDate.getFullYear();
			var _MM = paddingStr(_curDate.getMonth() + 1 + '');
			var _DD = paddingStr(_curDate.getDate() + '');
			return `${_YY}-${_MM}-${_DD}`			
		}		
	}
}
</script>

<style scoped>
.comment{background-color: #fff;  margin:15px 0; padding-bottom:25px;  position:relative;}
.comment h3 {color: #333; font-size: 18px;  padding: 25px 0 15px; margin:0 20px;}
.comment-main{ margin:0 20px; border-top:1px solid #EEEEEE}
.header{ width:45px; height:45px;  text-transform: uppercase; line-height:45px; font-size:30px; background:rgba(46,167,224,0.6); font-weight:bold; border-radius:5px;}
.name{ font-size:14px;}
.comment-main >>> .ant-comment-actions{ margin-top:8px;}
.comment-content{ padding:0 20px 20px;}
.comment-textbox{ width:100%; margin-bottom:20px;}
.comment-textarea{ outline:none;  border-radius:0; font-family:'Source Sans Pro',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif; resize:none; width:100%;  height:150px; }
.comment-btns{}
.replay{ font-size:13px; color:#999;}
.replay:hover{ text-decoration:underline; color:#1890FF;}
.comment-btn{ width:100px;  height:36px;}
.comment-input{ border-radius:0; width:240px; height:36px;}
.comment-input >>> .ant-input{border-radius:0; width:240px; height:36px;}
.comment-tips{ color:#FF6262; padding:0 20px; line-height:1.8;}
</style>
